package com.mac.userinfo.usermanage.action;

import com.github.pagehelper.PageInfo;
import com.mac.common.util.BusinessException;
import com.mac.common.util.ExcelUtil;
import com.mac.core.activemq.JMSConsumer;
import com.mac.core.activemq.JMSProducer;
import com.mac.core.dao.ARedisDao;
import com.mac.core.page.PageBean;
import com.mac.core.vo.RedisVO;
import com.mac.userinfo.usermanage.service.IUserManageService;
import com.mac.userinfo.usermanage.vo.UserInfoVO;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.jms.Destination;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;
import java.util.*;

/**
 * 登陆控制器
 * @author macao
 */
@Controller
public class UserManageAction {
    private final Logger log =  LoggerFactory.getLogger(this.getClass());
    @Autowired
    private IUserManageService iUserManageService;

    @Autowired
    private ARedisDao redisDao;

    @Autowired
    WebApplicationContext applicationContext;

    @Autowired
    private JMSProducer jmsProducer;

    /**
     *
     * @param request
     * @param page   分页对象
     * @param principal
     * @param vo
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/main_menu")
    @ResponseBody
    public ModelAndView mainMenu(HttpServletRequest request, PageBean page, Principal principal, UserInfoVO vo ,
                                 ModelAndView model) throws Exception  {

        /*log.info("Redi保存信息START＝＝＝＝");
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "Tom");
        map.put("age", 22);
        list.add(map);
        redisDao.put("data", list, -1);
        log.info("Redis保存所有信息END＝＝＝＝");
        redisDao.empty();
        log.info("Redis查询所有信息START＝＝＝＝");
        Object r = redisDao.get("data");
        log.info("Redis查询所有信息END＝＝＝＝");*/

        getAllUrl();
        page.setPageSize(10);
        String loginId = principal.getName();
        String authorityKind = "ADMIN";
        PageInfo<UserInfoVO> pageInfo = iUserManageService.queryAllInfo(vo, page.getCurrentPage(), page.getPageSize() );
        request.getSession().setAttribute("authorityKindMap", authorityKind);
        model.addObject("loginId",loginId);
        model.addObject("isLogout", true);
        model.addObject("pageInfo", pageInfo);
        model.setViewName("views/userinfo/usermanage/main_menu");
        // 发布消息
        log.info("发布消息：" + request.getRequestedSessionId());
        Destination destination = new ActiveMQTopic("springboot.topic");
        jmsProducer.sendMessage(destination,"hello," + request.getRequestedSessionId());
        return model;
    }

    /**
     * 导入Excel数据
     *
     * @param request 客户端请求
     * @param excelFile 导入的Excel文件
     * @return result 导入结果
     */
    @RequestMapping(value = "/addbatch", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addBatch (HttpServletRequest request, MultipartFile excelFile) {
        boolean result = false;
        Map<String, Object> mapMsg = new HashMap<String, Object>();
        String msg = "";
        String fileName = "";
        try {
                if (null != excelFile) {
                    // 文件名
                    fileName = excelFile.getName();
                    fileName = fileName.replace("\\", "|");

                    // 检查文件后缀格式
                    String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    /**
                     * 要保存的字段
                     */
                    int num = iUserManageService.addBatch(excelFile.getInputStream(), null, null);
                    result = true;
                    msg = "成功导入 " + num + " 条数据！";
                    log.info(msg);
                }

        } catch (BusinessException e) {
            log.error("保存失败！ 原因：" + e.getMessage());
            result = false;
            msg =  e.getMessage();
        } catch (Exception e) {
            log.error("保存失败！ 原因：" + e.getMessage());
            result = false;
            msg = "保存失败，请检查模板！";
        }
        mapMsg.put("result", result);
        mapMsg.put("msg", msg);
        return mapMsg;
    }

    /**
     * 下载兑换码信息模板
     */
    @RequestMapping("/downloadexcel")
    public void downloadExcel (HttpServletRequest request, HttpServletResponse response, String sheetName, String fileName) {
        try {

            String columnTitle = "用户ID,用户姓名,密码,身份证,邮箱,电话,性别,年龄,婚姻状态,生日";
            String column = "USERID,USERNAME,USERPWD,TID,EMAIL,TEL,SEX,AGE,MARITALSTATUS,BIRTHDATE";
            ExcelUtil.downloadExcelModel(sheetName, true, 0, fileName, columnTitle, column, null, 0, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<String> getAllUrl(){
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        //获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        List<String> urlList = new ArrayList<>();
        for (RequestMappingInfo info : map.keySet()){
            //获取url的Set集合，一个方法可能对应多个url
            Set<String> patterns = info.getPatternsCondition().getPatterns();
            for (String url : patterns){
                urlList.add(url);
            }
        }
        return urlList;
    }

}
